﻿using HPSocket;
using HPSocket.WebSocket;
using IntelligentGateway.Model;
using IntelligentGateway.Tools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentGateway.Services
{
    public class WSMessageProcess
    {

        public static async Task<bool> ProcessClientSendMessage(IWebSocketAgent sender, IntPtr connId, byte[] data)
        {
            WebSocketRequest request = DataUnPacket(data);
            if (request != null)
            {
                WebSocketResponse response = await CommServices.ReflectInvoke(request);
                if (response != null)
                {
                    string result = JsonConvert.SerializeObject(response);
                    byte[] bytes = Encoding.UTF8.GetBytes(result);
                    bool success = sender.Send(connId, OpCode.Text, bytes, bytes.Length);
                    return success;
                }
            }
            return true;
        }
        public static byte[] DataPacket(WebSocketRequest Request)
        {
            string result = JsonConvert.SerializeObject(Request);
            string encryptResult = SecureTools.Encrypt(result);
            byte[] data = Encoding.UTF8.GetBytes(encryptResult);
            return data;
        }
        public static byte[] DataPacket(string JsonData)
        {
            string result = JsonConvert.SerializeObject(JsonData);
            string encryptResult = SecureTools.Encrypt(result);
            byte[] data = Encoding.UTF8.GetBytes(encryptResult);
            return data;
        }
        public static WebSocketRequest DataUnPacket(byte[] Data)
        {
            string result = Encoding.UTF8.GetString(Data);           
            if (string.IsNullOrEmpty(result)) return null;
            try
            {
                WebSocketRequest request = JsonConvert.DeserializeObject<WebSocketRequest>(result);
                return request;
            }
            catch
            {
                return null;
            }
        }
    }
}
